package system

import (
	ArticleModel "blog/app/model/articles"
	core2 "blog/app/validates/core"
	"blog/core"
	"github.com/go-playground/validator/v10"
	"strings"
)

type Article struct{}

func (a *Article) Validate(data interface{}) (string, error) {
	var catExists validator.Func = func(fl validator.FieldLevel) bool {
		var count int64
		core.DbConnect.Model(&ArticleModel.Cate{}).Where("id = ?", fl.Field().Int()).Count(&count)
		return count > 0
	}
	var tagExists validator.Func = func(fl validator.FieldLevel) bool {
		var tagId string = fl.Field().String()
		var count int64
		tagIds := strings.Split(tagId, ",")
		core.DbConnect.Model(&ArticleModel.Tag{}).Where("id in ?", tagIds).Count(&count)
		return int(count) >= len(tagIds)
	}

	vv := validator.New()
	vv.RegisterValidation("ArticleCatExists", catExists)
	vv.RegisterValidation("ArticleTagExists", tagExists)
	if err := vv.Struct(data); err != nil {
		return a.errorMsg(err), err
	}

	return "", nil
}

func (a *Article) errorMsg(err interface{}) string {
	var validate *core2.Validate
	return validate.ErrorMsg(err, map[string]interface{}{
		"Title": "标题不能为空",
		"Password": map[string]string{
			"required_if": "必须设置密码",
		},
		"Album":   "必须相册不能为空",
		"Content": "内容不能为空",
		"MainImg": "文章图片不能为空",
		"Tid": map[string]string{
			"required":         "标签不能为空",
			"ArticleTagExists": "有相关标签不存在",
		},
		"Cid": map[string]string{
			"required":         "分类不能为空",
			"ArticleCatExists": "分类不存在",
		},
	})
}
